<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<link href="main.css" rel="stylesheet" type="text/css">

<title>SoftPlus</title><body>
<table border="0" align="center">
  <tr>
    <td width="150px"></td>
    <td width="1000px"><img src="banner-01n.gif" width="1000" height="90" alt="Softplus"></td>
  </tr>
  <tr>
    <td><?php
      require("navandset.php");
    ?></td>
<td valign="top">

<h1>Place Order</h1>

<?php
//Connect
$condet = GetGlobalConnectionOptions();
$con = mysql_connect($condet["server"],$condet["username"],$condet["password"]);
if (!$con)
{
	die("Could not connect: " . mysql_error());
}
//Select DB
mysql_select_db($condet["database"], $con);
$qry = "";

//Code
//Create the array to store customer details
$cust = array(
	"customer" => "",
	"surname" => "",
	"firstname" => ""
);
//Create the array to store order details
$currentorder = array(
	"orderid" => "",
	"customer" => "",
	"isfinal" => "",
	"totalprice" => "",
	"creationdate" => ""
);

//Create a variable to hold a message that tells the user what has just happened, if something has happened
$retmessage = "";

//Declare an array to store order item details
$orderitems;

$clear = false;

if($_SESSION["orderid"]  and $_POST["operation"] != "New Order")
{
	$qry = "SELECT orderid, customer, isfinal, totalprice, creationdate
		FROM tblorders
		WHERE orderid = ".$_SESSION["orderid"].";";
	$currentorder = mysql_fetch_array(mysql_query($qry));
	$qry = "SELECT customer, surname, firstname
		FROM tblcustomers
		WHERE customer='".$currentorder["customer"]."';";
	$cust = mysql_fetch_array(mysql_query($qry));
}

if($_POST)
{
	switch($_POST["operation"])
	{
		case "New Order":
			//Get customer email input from form
			$currentorder["customer"] = $_POST["customer"];
			
			//Get customer details from database
			$qry = "SELECT customer, surname, firstname
				FROM tblcustomers
				WHERE customer='".$currentorder["customer"]."';";
			$dcust = mysql_fetch_array(mysql_query($qry));
			//If the customer exists, create a new order in their name
			if($dcust)
			{
				$cust = $dcust;
				$qry = "INSERT INTO tblorders VALUES (NULL, '".$cust["customer"]."', '0', '0', NOW());";
				mysql_query($qry);
				$qry = "SELECT orderid, customer, isfinal, totalprice, creationdate
					FROM tblorders
					WHERE orderid = (
					SELECT MAX(orderid)
					FROM tblorders
					WHERE customer='".$cust["customer"]."');";
				$currentorder = mysql_fetch_array(mysql_query($qry));
				$_SESSION["orderid"] = $currentorder["orderid"];
				$_SESSION["ordertotal"] = 00000.00;
				$retmessage = "Created new order.";
			}
			else
			{
				$retmessage = "No records were found for customer with email ".$currentorder["customer"].".";
			};
			break;
		case "Add Item":
			if($currentorder["orderid"] != "")
			{
				if($_POST["addeditem"] == "NULL")
				{
					$retmessage = "No item selected.";
				}
				else
				{
					$qry = "SELECT COUNT(orderid) as numdup
						FROM tblorderitems
						WHERE orderid='".$currentorder["orderid"]."'
						AND item='".$_POST["addeditem"]."';";
					$numduparray = mysql_fetch_array(mysql_query($qry));
					$numdup = $numduparray["numdup"];
					if($numdup == "0")
					{
						$qry = "INSERT INTO tblorderitems
							VALUES ('".
							$currentorder["orderid"].
							"', '".
							$_POST["addeditem"].
							"', '1');";
						mysql_query($qry);
						$retmessage = "Add item with barcode ".$_POST["addeditem"];
					}
					else
					{
						$retmessage = "Item already exists in order.";
					};
				};
			}
			else
			{
				$retmessage = "Create an order before adding items.";
			};
			break;
		case "Update Quantities":
			if($currentorder["orderid"] != "")
			{
				$qry = "SELECT item
					FROM tblorderitems
					WHERE orderid='".$currentorder["orderid"]."';";
				$itemlist = mysql_query($qry);
				while($item = mysql_fetch_array($itemlist))
				{
					if($_POST[$item["item"]] != "")
					{
						if($_POST[$item["item"]] == "0")
						{
							$qry = "DELETE FROM tblorderitems
								WHERE orderid='".$currentorder["orderid"]."'
								AND item='".$item["item"]."';";
						}
						else
						{
							//Get the number of that item that are in stock
							$qry = "SELECT stock
								FROM tblitems
								WHERE item='".$item["item"]."';";
							$result = mysql_fetch_array(mysql_query($qry));
							$quant = $result["stock"];
							if($quant > $_POST[$item["item"]])
							{
								$quant = $_POST[$item["item"]];
							};
							$qry = "UPDATE tblorderitems
								SET quantity='".$quant."'
								WHERE orderid='".$currentorder["orderid"]."'
								AND item='".$item["item"]."';";
						};
						mysql_query($qry);
					};
				};
			};
			break;
		case "Cancel":
			if($currentorder["orderid"] != "")
			{
				$qry = "DELETE FROM tblorderitems
					WHERE orderid='".$currentorder["orderid"]."';";
				mysql_query($qry);
				$qry = "DELETE FROM tblorders
					WHERE orderid='".$currentorder["orderid"]."';";
				mysql_query($qry);
			};
			$clear = true;
			session_destroy();
			break;
		case "Finish":
			if($currentorder["orderid"] != "")
			{
				if($_SESSION["ordertotal"] > 99999.99)
				{
					$retmessage = "Maximum transaxtion is $99999.99.";
				}
				else
				{
					$qry = "UPDATE tblitems, tblorderitems
						SET tblitems.stock=tblitems.stock-tblorderitems.quantity
						WHERE tblitems.item=tblorderitems.item
						AND tblorderitems.orderid='".$currentorder["orderid"]."';";
					mysql_query($qry);
					$qry = "UPDATE tblorders
						SET isfinal='1',
						totalprice='".$_SESSION["ordertotal"]."'
						WHERE orderid='".$currentorder["orderid"]."';";
					mysql_query($qry);
					$clear = true;
					session_destroy();
				};
			};
			break;
	};
};

if($clear)
{
	$cust["customer"] = "";
	$cust["surname"] = "";
	$cust["firstname"] = "";
	$currentorder["orderid"] = "";
	$currentorder["customer"] = "";
	$currentorder["isfinal"] = "";
	$currentorder["totalprice"] = "";
	$currentorder["creationdate"] = "";
};

//If an order has been selected, then get a list of details to display to the user
if($currentorder["orderid"] != "")
{
	$qry = "SELECT tblorderitems.item, tblitems.name, tblitems.platform, tblitems.price, tblorderitems.quantity, tblitems.price*tblorderitems.quantity AS total
		FROM tblitems, tblorderitems
		WHERE tblorderitems.orderid='".$currentorder["orderid"]."'
		AND tblitems.item = tblorderitems.item;";
	$orderitems = mysql_query($qry);
};

?>

<form action="frmtrans.php" method="post">
<table border="1">
      <tr>
        <td width="150px"><h2>*Customer Email:</h2></td>
        <td><input type="text" name="customer" size="100" maxlength="100" <?php echo "value='".$currentorder["customer"]."' "; ?> /></td>
        <td><input type="submit" name="operation" value="New Order"></td>
      </tr>
      <tr>
        <td><h2>Customer Name:</h2></td>
        <td><h2><?php echo $cust["firstname"]." ".$cust["surname"]; ?></h2></td>
      </tr>
      <tr>
        <td><h2>Order Number:</h2></td>
        <td><h2><?php echo $currentorder["orderid"]; ?></h2></td>
      </tr>
      <tr>
        <td><h2>*Payment Details:</h2></td>
        <td><input type="text" name="payment" size="100" maxlength="100" <?php if($_POST and !$clear){echo "value='".$_POST["payment"]."' ";}; ?> /></td>
      </tr>
</table>
<table width="840px" border="1">
	<tr>
		<td><h3>Product Name</h3></td>
		<td width="140px"><h3>Price Per Unit (inc. GST)</h3></td>
		<td width="140px"><h3>Quantity</h3></td>
		<td width="140px"><h3>Total</h3></td>
	</tr>
	<?php
		$_SESSION["ordertotal"] = 00000.00;
		while($item = mysql_fetch_array($orderitems))
		{
			echo "<tr>";
			echo "<td align='middle'><a href='rptproductinfo.php?item=".$item["item"]."'><h5>".$item["name"]." - ".$item["platform"]."</h5></a></td>";
			echo "<td align='right'><h5>$".$item["price"]."</h5></td>";
			echo "<td align='middle'><input type='text' name='".$item["item"]."' size='4' maxlength='4' value='".$item["quantity"]."' /></td>";
			echo "<td align='right'><h5>$".$item["total"]."</h5></td>";
			echo "</tr>";
			$_SESSION["ordertotal"] += $item["total"];
		};
	?>
	<tr>
		<td></td><td></td><td><input type="submit" name="operation" value="Update Quantities"></td><td></td>
	</tr>
	<tr>
		<td></td><td></td><td><h5>Total</h5></td><td alig='right'><h5>$<?php echo $_SESSION["ordertotal"]; ?></h5></td>
	</tr>
</table>
<table border="0">
	<tr>
		<td>
			<select name="addeditem">
			<option value="NULL" selected="selected">Select an item</option>
			<?php
			$items = mysql_query("SELECT item, name, platform FROM tblitems;");
			while($item = mysql_fetch_array($items))
			{
				echo "<option value='".$item["item"]."'>".$item["name"]." - ".$item["platform"]."</option>";
			};
			?>
			</select>
		</td>
		<td><input type="submit" name="operation" value="Add Item"></td>
	</tr>
</table>
<input type="submit" name="operation" value="Cancel">
<input type="submit" name="operation" value="Finish">
</form>
<h2>Fields marked with a * are required.</h2>
<h2><?php echo $retmessage ?></h2>

<?php
//Disconnect
mysql_close($con);
?>

</td>
  </tr>
</table>
</body>

</html>
